from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from django.contrib.auth.hashers import make_password, check_password
from django.core.mail import send_mail
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from app.forms import LoginForm
from app.models import User
from session import settings
from session.settings import EMAIL_FROM


def refresh_cap(request):
    form = LoginForm()
    print(type(form))
    print(form)
    return JsonResponse({"data": str(form)})


def register(request):
    print(request.method)
    if (request.method == "GET"):
        return render(request, "app/register.html")
    elif (request.method == "POST"):
        username = request.POST.get("username")
        password = request.POST.get("password")
        password1 = request.POST.get("password1")
        if password != password1:
            print("密码err")
            return redirect("user/login")
        else:
            stu = User.objects.filter(username=username)
            # 用户已存在
            if stu:
                print("用户已经存在")
                return redirect("/user/register")
            else:
                print("kkk")
                # 对密码进行加密
                password = make_password(password)

                stu1 = User(username=username, password=password)
                stu1.save()
                return redirect("/user/login")


def login(request):
    # print(request.method)
    if (request.method == "GET"):
        form = LoginForm()
        return render(request, "app/login.html", {"captcha": form})

    elif (request.method == "POST"):
        form = LoginForm(request.POST)
        if not form.is_valid():
            print("验证码错了")
            return redirect("/user/login/")

        username = request.POST.get("username")
        password = request.POST.get("password")
        stu = User.objects.filter(username=username)
        password1 = stu[0].password
        # 解密
        isTrue = check_password(password, password1)
        if isTrue and stu:
            print("通过")
            # 存储session
            request.session["user_session"] = username
            return redirect("/")
        else:
            print("err")
            return render(request, "app/login.html")


def logout(request):
    # 删除session
    request.session.flush()
    return redirect("/user/login")


# 发送单个邮件
def sendone_email(request):
    email_title = '这是邮件的标题---django 邮件发送one'
    email_body = '学习py,节约时间---one'
    email = '1925541533@qq.com'  # 对方的邮箱
    send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])

    if send_status:
        return HttpResponse("发⼀封邮件success")
    else:
        return HttpResponse("发⼀封邮件err")


# 群发邮件
def sendmany_email(request):
    email_title = '这是邮件的标题---django 邮件发送many'
    email_body = '学习py,节约时间---many 点击下方链接前往学习 https://www.bilibili.com/video/BV1jZ4y1p7zQ?p=449></a>'
    email = ['1746502689@qq.com', '1925541533@qq.com']  # 对方的邮箱
    send_status = send_mail(email_title, email_body, EMAIL_FROM, email)

    if send_status:
        return HttpResponse("发多封邮件success")
    else:
        return HttpResponse("发多封邮件err")


# 不使用表单 前后端分离使用
def output_yzm(request):
    #验证码验证
    if request.method == "POST":
        print(request.POST)
        yzm = request.POST.get('yzm', '')
        hashkey = request.POST.get('code')
        # 根据key获取验证码对象
        cap = CaptchaStore.objects.filter(hashkey=hashkey).first()
        if cap:  # 存在
            if cap.response == yzm.lower():
                return HttpResponse("验证成功")
        return HttpResponse("验证失败")
    else:
        # 生成hashkey和image_url 生成验证码
        new_key = CaptchaStore.pick()
        image_url = captcha_image_url(new_key)
        print("---------------")
        return render(request, 'app/vc.html', locals())
